package com.crop.back.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crop.back.common.enums.Deleted;
import com.crop.back.common.enums.RoleEnum;
import com.crop.back.common.utils.ResultBean;
import com.crop.back.common.utils.UserHolder;
import com.crop.back.dto.ProcessingBatchDTO;
import com.crop.back.dto.ProductDTO;
import com.crop.back.entity.ProcessingBatch;
import com.crop.back.entity.Processor;
import com.crop.back.entity.Product;
import com.crop.back.entity.ProductCategory;
import com.crop.back.entity.Supplier;
import com.crop.back.service.ProcessingBatchService;
import com.crop.back.service.ProcessorService;
import com.crop.back.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;

/**
 * <p>
 * 加工批次表 前端控制器
 * </p>
 *
 * @author 作者
 * @since 2025-01-20
 */
@RestController
@RequestMapping("/processing-batch")
@Slf4j
public class ProcessingBatchController {

    @Resource
    private ProcessingBatchService batchService;

    @Resource
    private ProductService productService;
    @Resource
    private ProcessorService processorService;

    @GetMapping("/getBatchNo")
    public ResultBean getBatchNo() {
        return ResultBean.ok(batchService.getBatchNo());
    }

    @PostMapping("/list")
    public ResultBean getAll(@RequestBody ProcessingBatchDTO batchDTO) {
        try {
            Integer page = batchDTO.getPage();
            Integer pageSize = batchDTO.getPageSize();
            Page<ProcessingBatch> pageInfo = new Page<>(page, pageSize);

            Map<Long, String> map1 = processorService
                    .list(new LambdaQueryWrapper<Processor>().eq(Processor::getDeleted, Deleted.NOT_DELETED.getCode()))
                    .stream()
                    .collect(Collectors.toMap(
                            Processor::getId,
                            Processor::getName
                    ));
            Map<Long, String> map2 = productService
                    .list(new LambdaQueryWrapper<Product>().eq(Product::getDeleted, Deleted.NOT_DELETED.getCode()))
                    .stream()
                    .collect(Collectors.toMap(
                            Product::getId,
                            Product::getName
                    ));

            LambdaQueryWrapper<ProcessingBatch> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProcessingBatch::getDeleted, Deleted.NOT_DELETED.getCode());
            if (UserHolder.getUser().getRoleId() == RoleEnum.PROCESSOR.getCode()) {
                queryWrapper.eq(ProcessingBatch::getProcessorId, UserHolder.getUser().getReferenceId());
            }
            Page<ProcessingBatch> pageRes = batchService.page(pageInfo, queryWrapper);

            List<ProcessingBatchDTO> collect = pageRes.getRecords()
                    .stream()
                    .map(item -> {
                        ProcessingBatchDTO dto = BeanUtil.copyProperties(item, ProcessingBatchDTO.class);
                        dto.setProcessorName(map1.getOrDefault(dto.getProcessorId(), "暂无"));
                        dto.setProductName(map2.getOrDefault(dto.getProductId(), "暂无"));
                        return dto;
                    }).collect(Collectors.toList());
            return ResultBean.ok(collect, pageRes.getTotal());
        } catch (Exception e) {
            return ResultBean.fail("查找失败");
        }
    }

    @PostMapping("/get")
    public ResultBean getByCondition(@RequestBody ProcessingBatchDTO batchDTO) {
        try {
            Integer page = batchDTO.getPage();
            Integer pageSize = batchDTO.getPageSize();
            Page<ProcessingBatch> pageInfo = new Page<>(page, pageSize);

            Map<Long, String> map1 = processorService
                    .list(new LambdaQueryWrapper<Processor>().eq(Processor::getDeleted, Deleted.NOT_DELETED.getCode()))
                    .stream()
                    .collect(Collectors.toMap(
                            Processor::getId,
                            Processor::getName
                    ));
            Map<Long, String> map2 = productService
                    .list(new LambdaQueryWrapper<Product>().eq(Product::getDeleted, Deleted.NOT_DELETED.getCode()))
                    .stream()
                    .collect(Collectors.toMap(
                            Product::getId,
                            Product::getName
                    ));

            List<Long> processorIdList = processorService
                    .list(new LambdaQueryWrapper<Processor>()
                            .eq(Processor::getDeleted, Deleted.NOT_DELETED.getCode())
                            .like(batchDTO.getProcessorName() != null, Processor::getName, batchDTO.getProcessorName()))
                    .stream()
                    .map(Processor::getId)
                    .toList();

            List<Long> productIdList = productService
                    .list(new LambdaQueryWrapper<Product>()
                            .eq(Product::getDeleted, Deleted.NOT_DELETED.getCode())
                            .like(batchDTO.getProductName() != null, Product::getName, batchDTO.getProductName()))
                    .stream()
                    .map(Product::getId)
                    .toList();

            LambdaQueryWrapper<ProcessingBatch> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProcessingBatch::getDeleted, Deleted.NOT_DELETED.getCode());
            queryWrapper.eq(batchDTO.getBatchNo() != null, ProcessingBatch::getBatchId, batchDTO.getBatchNo());
            if (batchDTO.getProcessorName() != null && processorIdList.isEmpty()) {
                return ResultBean.ok();
            }
            if (batchDTO.getProductName() != null && productIdList.isEmpty()) {
                return ResultBean.ok();
            }
            queryWrapper.in(!processorIdList.isEmpty(), ProcessingBatch::getProcessorId, processorIdList);
            queryWrapper.in(!productIdList.isEmpty(), ProcessingBatch::getProductId, productIdList);
            if (UserHolder.getUser().getRoleId() == RoleEnum.PROCESSOR.getCode()) {
                queryWrapper.eq(ProcessingBatch::getProcessorId, UserHolder.getUser().getReferenceId());
            }

            Page<ProcessingBatch> pageRes = batchService.page(pageInfo, queryWrapper);

            List<ProcessingBatchDTO> collect = pageRes.getRecords()
                    .stream()
                    .map(item -> {
                        ProcessingBatchDTO dto = BeanUtil.copyProperties(item, ProcessingBatchDTO.class);
                        dto.setProcessorName(map1.getOrDefault(dto.getProcessorId(), "暂无"));
                        dto.setProductName(map2.getOrDefault(dto.getProductId(), "暂无"));
                        return dto;
                    }).collect(Collectors.toList());
            return ResultBean.ok(collect, pageRes.getTotal());
        } catch (Exception e) {
            return ResultBean.fail("查找失败");
        }
    }

    @PostMapping("/save")
    public ResultBean addOrUpdate(@RequestBody ProcessingBatchDTO batchDTO) {
        try {
            ProcessingBatch processingBatch = BeanUtil.copyProperties(batchDTO, ProcessingBatch.class);
            if (processingBatch.getId() == null) {
                batchService.save(processingBatch);
                return ResultBean.ok("添加成功");
            } else {
                batchService.updateById(processingBatch);
                return ResultBean.ok("修改成功");
            }
        } catch (Exception e) {
            log.error("保存失败: " + e.getMessage());
            return ResultBean.fail("保存失败");
        }

    }

    @DeleteMapping("/delete/{id}")
    public ResultBean delete(@PathVariable("id") Long id) {
        try {
            LambdaUpdateWrapper<ProcessingBatch> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ProcessingBatch::getId, id);
            updateWrapper.set(ProcessingBatch::getDeleted, Deleted.DELETED.getCode());
            batchService.update(updateWrapper);
            return ResultBean.ok();
        } catch (Exception e) {
            return ResultBean.fail("删除失败");
        }
    }

}
